#include <Wire.h>

// HMC5883L I2C地址
#define HMC5883L_ADDRESS 0x1E

void setup() {
  Serial.begin(9600);
  Wire.begin();
  // 初始化HMC5883L
  Wire.beginTransmission(HMC5883L_ADDRESS);
  Wire.write(0x02); // 设置寄存器为连续测量模式
  Wire.write(0x00); // 设置连续测量模式为默认值
  Wire.endTransmission();
}

void loop() {
  // 读取HMC5883L的磁场数据
  Wire.beginTransmission(HMC5883L_ADDRESS);
  Wire.write(0x03); // 设置寄存器为X轴磁场寄存器
  Wire.endTransmission(false);
  Wire.requestFrom(HMC5883L_ADDRESS, 6); // 读取6个字节的数据
  uint8_t data[6];
  for (int i = 0; i < 6; i++) {
    data[i] = Wire.read();
  }

  // 解析磁场数据
  int16_t x = (data[0] << 8) | data[1];
  int16_t z = (data[2] << 8) | data[3];
  int16_t y = (data[4] << 8) | data[5];

  // 计算方位角度
  float heading = atan2(y, x);
  if (heading < 0) {
    heading += 2 * PI;
  }

  // 将弧度转换为度数
  float headingDegrees = heading * 180 / PI;
  // 打印方位角度
  Serial.print("方位角度: ");
  Serial.println(headingDegrees);

  // 将度数转换为东南西北方向
  String direction;
  if (headingDegrees >= 22.5 && headingDegrees < 67.5) {
    direction = "东北";
  } else if (headingDegrees >= 67.5 && headingDegrees < 112.5) {
    direction = "东";
  } else if (headingDegrees >= 112.5 && headingDegrees < 157.5) {
    direction = "东南";
  } else if (headingDegrees >= 157.5 && headingDegrees < 202.5) {
    direction = "南";
  } else if (headingDegrees >= 202.5 && headingDegrees < 247.5) {
    direction = "西南";
  } else if (headingDegrees >= 247.5 && headingDegrees < 292.5) {
    direction = "西";
  } else if (headingDegrees >= 292.5 && headingDegrees < 337.5) {
    direction = "西北";
  } else {
    direction = "北";
  }

  // 打印方向
  Serial.print("方向: ");
  Serial.println(direction);

  delay(1000);
}